package com.jieshuibao.controller;

import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jieshuibao.common.config.Const;
import com.jieshuibao.common.config.Global;
import com.jieshuibao.common.res.BaseRes;
import com.jieshuibao.model.db.AnswerUser;
import com.jieshuibao.model.db.Praise;
import com.jieshuibao.model.db.Question;
import com.jieshuibao.model.db.QuestionEx;
import com.jieshuibao.model.db.QuestionExample;
import com.jieshuibao.model.db.QuestionExample.Criteria;
import com.jieshuibao.model.db.QuestionExample.Criterion;
import com.jieshuibao.model.db.QuestionUserKey;
import com.jieshuibao.model.domain.AnswerUserRequest;
import com.jieshuibao.model.domain.CookieUser;
import com.jieshuibao.model.domain.OnlookReq;
import com.jieshuibao.model.domain.OnlookSerarchRes;
import com.jieshuibao.model.domain.PayReq;
import com.jieshuibao.model.domain.SerarchExample;
import com.jieshuibao.service.AnswerUserService;
import com.jieshuibao.service.CounselorDutyService;
import com.jieshuibao.service.PraiseService;
import com.jieshuibao.service.QuestionExService;
import com.jieshuibao.service.QuestionService;
import com.jieshuibao.service.QuestionUserService;
import com.jieshuibao.service.SecretlyService;
import com.jieshuibao.service.WeiXinPayService;
import com.jieshuibao.util.DateUtils;
import com.jieshuibao.util.IKAnalyserUtil;
import com.jieshuibao.util.IdGen;
import com.jieshuibao.util.StringUtils;
import com.jieshuibao.wx.po.WxAppPayReq;
import com.jieshuibao.wx.po.WxAppPayRes;
import com.jieshuibao.wx.po.WxJsPayReq;
import com.jieshuibao.wx.po.WxjsPayRes;
import com.jieshuibao.wx.util.PayCommonUtil;

/**
 * @author :liuxb@jieshuibao.com
 * @version ：2018年8月14日 下午3:18:13
 * 类说明
 */
@Controller
@RequestMapping("/onlook")
public class OnLooksController {
	
	private static final Logger logger = LoggerFactory
			.getLogger("OnLooksController.class");
	private static final ObjectMapper mapper = new ObjectMapper();
	
	@Resource
	private QuestionUserService questionUserService;
	
	@Resource
	private QuestionService questionService;
	
	@Resource
	private AnswerUserService answerUserService;
	
	@Resource
	private CounselorDutyService counselorDutyService;
	
	@Resource
	private SecretlyService SecretlyService;
	
	@Resource
	private WeiXinPayService weiXinPayService;
	
	@Resource
	private QuestionExService questionExService;
	
	@Resource
	private PraiseService praiseService;
	
	
	@Value("${price.num}")
	private double priceNum;
	
	/**
	 * 围观授权
	 * @param request
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/look/authorized",method=RequestMethod.POST)
	@ResponseBody
	public Object onlookQuestion(HttpServletRequest request,
			@RequestBody(required=false) AnswerUserRequest req){
		BaseRes<AnswerUser> res = new BaseRes<AnswerUser>();
		try {
			logger.debug("接收：" + mapper.writeValueAsString(req));
			request.getHeader("cookieId");
			
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
			String phoneNumber = cookieUser.getPhoneNumber();
				
			
			
			if (req==null) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			String questionUuid = req.getQuestionUuid();
			if (StringUtils.isBlank(questionUuid)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			Question question = questionService.getQuestionByUuid(questionUuid);
			if (question!=null) {
				Integer status = question.getStatus();
				if (status!=null&&status==3) {
					
					String phoneNum = question.getPhoneNum();
					if (!phoneNum.equals(phoneNumber)) {
						QuestionUserKey questionUserKey2 = new QuestionUserKey();
						questionUserKey2.setPhoneNumber(phoneNumber);
						questionUserKey2.setQuestionUuid(questionUuid);
						QuestionUserKey questionUserKey = questionUserService
								.getQuestionUserKeys(questionUserKey2);
						if (questionUserKey==null) {
							//需要购买
							res.setCode(BaseRes.SUCCESS_CODE);
							res.setDes(BaseRes.SUCCESS_DES);
							return res;
						}
					}
					
					List<AnswerUser> answerUsers = answerUserService
							.getAnswerUserByQUid(questionUuid);
					if (answerUsers!=null&&answerUsers.size()>0) {
						AnswerUser answerUser = answerUsers.get(0);
						Praise praise = praiseService.getPraise(phoneNumber, answerUser.getUuid());
						if (praise!=null) {
							Integer praiseNum = praise.getPraiseNum();
							Integer treadNum = praise.getTreadNum();
							if (praiseNum==null) {
								praiseNum=0;
							}
							if (treadNum==null) {
								treadNum=0;
							}
							answerUser.setPraiseNum(praiseNum);
							answerUser.setTreadNum(treadNum);
						}
						
						String counselorDuty = answerUser.getCounselorDuty();
						String dutyName = counselorDutyService.getCounselorDutyName(counselorDuty);
						answerUser.setCounselorDuty(dutyName);
						
						res.setData(answerUser);
						res.setCode(BaseRes.SUCCESS_CODE);
						res.setDes(BaseRes.SUCCESS_DES);
						return res;
					}else {
						res.setCode(BaseRes.ERRORPARAM_CODE);
						res.setDes(BaseRes.ERRORPARAM_DES);
						return res;
					}
				}else {
					res.setCode(BaseRes.ERRORPARAM_CODE);
					res.setDes(BaseRes.ERRORPARAM_DES);
					return res;
				}
				
			}else {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes(BaseRes.FAIL_DES);
			
			return res;
		}
		
	}
	/**
	 * 围观支付
	 * @param request
	 * @param req
	 * @return
	 */
	@RequestMapping(value="/look/buy",method=RequestMethod.POST)
	@ResponseBody
	public Object buyQuestion(HttpServletRequest request,
			@RequestBody(required=false) PayReq req){
		
		BaseRes<String> res = new BaseRes<String>();
		
		try {
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
			String phoneNumber = cookieUser.getPhoneNumber();
			double balance = cookieUser.getBalance();
			Double vipBalance = cookieUser.getVipBalance();
			
			if (req==null) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			String uuid = req.getUuid();
			String uuid2 = IdGen.uuid();
			if (StringUtils.isBlank(uuid)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			Question question = questionService.getQuestionByUuid(uuid);
			if (question!=null) {
				Integer status = question.getStatus();
				if (status==null||status!=3) {
					res.setCode(BaseRes.ERRORPARAM_CODE);
					res.setDes(BaseRes.ERRORPARAM_DES);
					return res;
				}
			}else {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			QuestionUserKey questionUserKey2 = new QuestionUserKey();
			questionUserKey2.setPhoneNumber(phoneNumber);
			questionUserKey2.setQuestionUuid(uuid);
			QuestionUserKey questionUserKey = questionUserService
					.getQuestionUserKeys(questionUserKey2);
			if (questionUserKey!=null) {
				//已购买过
				res.setCode(BaseRes.FAIL_CODE);
				res.setDes("不能重复购买！");
				return res;
			}
			String payType = req.getPayType();
			double money = req.getMoney();
			if (priceNum!=money) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes("支付金额错误！");
				return res;
			}
			if (StringUtils.isBlank(payType)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			if (payType.equals("balance")) {
				//余额支付
				if (money>balance) {
					res.setCode(BaseRes.FAIL_CODE);
					res.setDes("余额不足！");
					return res;
				}
				boolean buyQuestion = SecretlyService.buyQuestion(uuid,uuid2, phoneNumber, payType, money);
				if (!buyQuestion) {
					res.setCode(BaseRes.FAIL_CODE);
					res.setDes("支付失败！");
					return res;
				}else {
					res.setCode(BaseRes.SUCCESS_CODE);
					res.setDes(BaseRes.SUCCESS_DES);
					return res;
				}
				
				
			}else  if (payType.equals("VipBalance")) {
				if (money>vipBalance) {
					res.setCode(BaseRes.FAIL_CODE);
					res.setDes("顾问卡余额不足！");
					return res;
				}
				boolean buyQuestion = SecretlyService.buyQuestion(uuid,uuid2, phoneNumber, payType, money);
				
				if (!buyQuestion) {
					res.setCode(BaseRes.FAIL_CODE);
					res.setDes("支付失败！");
					return res;
				}else {
					res.setCode(BaseRes.SUCCESS_CODE);
					res.setDes(BaseRes.SUCCESS_DES);
					return res;
				}
			}else if (payType.equals("weixin")) {
				boolean buyQuestion = SecretlyService.buyQuestion(uuid,uuid2, phoneNumber, payType, money);
				if (!buyQuestion) {
					res.setCode(BaseRes.FAIL_CODE);
					res.setDes("支付失败！");
					return res;
				}
				int source = req.getSource();
				if (source==1) {
					String code = req.getCode();
					
					WxJsPayReq wxreq = new WxJsPayReq();
					wxreq.setCode(code);
					wxreq.setPhone(phoneNumber);
					wxreq.setUnitPrice(money);
					wxreq.setProductName("围观");
					wxreq.setProductType(Const.TTK);
					wxreq.setProductId(uuid2);
					WxjsPayRes jssdPayRes = (WxjsPayRes) weiXinPayService
							.jSSDKPayInfo(wxreq, request);
					return jssdPayRes;
					
				}else {
					WxAppPayReq wxAppPayReq = new WxAppPayReq();
					double price = money;
					wxAppPayReq.setUnitPrice(price);
					wxAppPayReq.setProductName("围观");
					wxAppPayReq.setPhone(phoneNumber);
					wxAppPayReq.setProductType(Const.TTK);
					wxAppPayReq.setProductId(uuid2);
					WxAppPayRes appPay = (WxAppPayRes) weiXinPayService
							.appPay(wxAppPayReq,
									request);
					
					return appPay;
				}
			
			}
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes(BaseRes.FAIL_DES);
		}
		return res;
	}
	
	@RequestMapping(value="/look/list",method=RequestMethod.POST)
	@ResponseBody
	public  Object hotRecommendQquestion(HttpServletRequest request,@RequestBody(required=false) OnlookReq req){
		
		BaseRes<List<QuestionEx>> res = new BaseRes<List<QuestionEx>>();
		
		try {
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
			String phoneNumber = cookieUser.getPhoneNumber();
			
			if (req==null) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			int sinceId = req.getSinceId();
			int maxId = req.getMaxId();
			
			String type = req.getType();
			if (StringUtils.isBlank(type)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
				
			}
			if (type.equals("recom")||type.equals("hot")) {
				if (maxId>10) {
					sinceId=6;
					maxId=10;
				}
			}
			QuestionExample questionExample = new QuestionExample();
			questionExample.setPageIndex(sinceId - 1);
			questionExample.setPageSize(maxId - sinceId + 1);
			Criteria createCriteria = questionExample.createCriteria();
			
			if (type.equals("recom")) {
				
				createCriteria.andRecomGreaterThan(0);
				questionExample.setOrderByClause("question.recom desc,question.date desc");
				
			}else if (type.equals("hot")) {
				Date weekime = DateUtils.getWeekime();//当天零点
				Date addDate = DateUtils.addDate(weekime, -7);//七天前零点
				createCriteria.andHotNotEqualTo(0);
				createCriteria.andRecomEqualTo(0);
				Criteria andDateBetween = createCriteria.andDateBetween(addDate, weekime);
				
				int i = questionService.countQuestion(questionExample);
				if (i<10) {
					List<Criterion> criteria = createCriteria.getCriteria();
					criteria.remove(andDateBetween);
					Date addDates = DateUtils.addDate(weekime, -30);//30天前零点
					createCriteria.andDateBetween(addDates, weekime);
				}
				
				questionExample.setOrderByClause("question_user.lookNum desc,question.date desc");
			}else {
				questionExample.setOrderByClause("question.date desc");
			}
			createCriteria.andStatusEqualTo(3);
			createCriteria.andPayStatusEqualTo(PayCommonUtil.PAYSUCCESS_STATUS);
			createCriteria.andDelFlagEqualTo(Global.SHOW);
			
			List<QuestionEx> onlookQuestion = questionExService.getOnlookQuestion(questionExample);
			for (QuestionEx question : onlookQuestion) {
				String uuid = question.getUuid();
				
				QuestionUserKey questionUserKey2 = new QuestionUserKey();
				questionUserKey2.setPhoneNumber(phoneNumber);
				questionUserKey2
				.setQuestionUuid(uuid);
				QuestionUserKey questionUserKey = questionUserService
						.getQuestionUserKeys(questionUserKey2);
				if (question.getPhoneNumber().equals(phoneNumber)
						|| questionUserKey != null) {
					question.setStatus(1);// 自己公开的和查看过的
					
				} else {
					question.setStatus(2);// 没有偷看过的
				}
			/*	List<Answer> answers = answerUserService.getAnswer(
						question.getUuid(), 2);
				if (null != answers&&answers.size()>0) {
					Answer answer = answers.get(0);
					
					question.setApproveNum(answer.getApproveNum());// 赞成数目
				}*/
				
				if (type.equals("recom")||type.equals("hot")) {
					String annoStatus = question.getAnnoStatus();
					if (annoStatus.equals("1")) {
						Question question2 = new Question();
						question2.setUuid(uuid);
						question2.setAnnoStatus("0");
						questionService.updateQuestion(question2);
						
					}
					
				}
			}
			res.setCode(BaseRes.SUCCESS_CODE);
			res.setDes(BaseRes.SUCCESS_DES);
			res.setData(onlookQuestion);
			res.setMaxId(sinceId+ onlookQuestion.size() - 1);
			res.setSinceId(sinceId);
			res.setRows(onlookQuestion.size());
			
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes(BaseRes.FAIL_DES);
		}
		
		return res;
		
	}
	
	@RequestMapping(value="/serarch",method=RequestMethod.POST)
	@ResponseBody
	public Object onLookQuestionSerarch(HttpServletRequest request,@RequestBody(required=false) OnlookReq req){
		//BaseRes<List<QuestionEx>> res = new BaseRes<List<QuestionEx>>();
		OnlookSerarchRes res = new OnlookSerarchRes();
		
		try {
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
			String phoneNumber = cookieUser.getPhoneNumber();
			if (req==null) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			String content = req.getContent();
			if (StringUtils.isBlank(content)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
				
			}
			
			int sinceId = req.getSinceId();
			int maxId = req.getMaxId();
			
			SerarchExample serarchExample = new SerarchExample();
			serarchExample.setPageIndex(sinceId - 1);
			serarchExample.setPageSize(maxId - sinceId + 1);
			List<String> list = IKAnalyserUtil.segmentRemoveSingle(content);
			serarchExample.setSerarchList(list);
			res.setSegments(list);
			List<QuestionEx> data = questionExService.getOnlookSercher(serarchExample);
			for (QuestionEx question : data) {
				String uuid = question.getUuid();
				
				QuestionUserKey questionUserKey2 = new QuestionUserKey();
				questionUserKey2.setPhoneNumber(phoneNumber);
				questionUserKey2
				.setQuestionUuid(uuid);
				QuestionUserKey questionUserKey = questionUserService
						.getQuestionUserKeys(questionUserKey2);
				if (question.getPhoneNumber().equals(phoneNumber)
						|| questionUserKey != null) {
					question.setStatus(1);// 自己公开的和查看过的
					
				} else {
					question.setStatus(2);// 没有偷看过的
				}
			}
			res.setCode(BaseRes.SUCCESS_CODE);
			res.setDes(BaseRes.SUCCESS_DES);
			res.setData(data);
			res.setMaxId(sinceId+ data.size() - 1);
			res.setSinceId(sinceId);
			res.setRows(data.size());
			return res;
		} catch (Exception e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes(BaseRes.FAIL_DES);
			return res;
		}
	}
	@RequestMapping(value="/wx/onlookAuthorized")
	@ResponseBody
	public Object wxOnlookauthorized(HttpServletRequest request,@RequestParam(required=false) String uuid){
		BaseRes<String> res = new BaseRes<String>();
		try {
			logger.info("接收：" + mapper.writeValueAsString(uuid));
			request.getHeader("cookieId");
			
			CookieUser cookieUser = (CookieUser)request.getAttribute("cookieUser");
			String phoneNumber = cookieUser.getPhoneNumber();
			if (StringUtils.isBlank(uuid)) {
				res.setCode(BaseRes.ERRORPARAM_CODE);
				res.setDes(BaseRes.ERRORPARAM_DES);
				return res;
			}
			Map<String, Object> resMap = questionExService.onlookAuthorized(phoneNumber, uuid);
			return resMap;
		} catch (JsonProcessingException e) {
			e.printStackTrace();
			res.setCode(BaseRes.FAIL_CODE);
			res.setDes(BaseRes.FAIL_DES);
			return res;
		}
		
	}
}
